<template>
    <Suspense>
        <template #default>
            <CanvasTree></CanvasTree>
        </template>
    </Suspense>
    <el-radio-group v-model="radio" class="radioEl">
        <el-radio :value="0">
            <el-button @click="mailSettingFunc">邮箱设置</el-button>
        </el-radio>
        <el-radio :value="1">
            <el-tooltip content="IOS用户专用！" placement="top" :enterable="false" :open-delay="1000">
                <el-button @click="barkSettingFunc">Bark设置</el-button>
            </el-tooltip>
        </el-radio>
        <el-radio :value="2" disabled>短信设置</el-radio>
    </el-radio-group>

    <!-- 通知设置对话框 start-->
    <el-dialog :title="title" width="450px" append-to-body draggable v-model="settingOuterVisible">
        <el-row :gutter="15">
            <el-form :model="formData" :rules="rules" :size="formSize" label-width="90px" ref="formRef"
                style="max-width: 600px">
                <el-col :span="24" v-if="formData.type == 0">
                    <el-form-item label="邮箱" prop="mail">
                        <el-input v-model="formData.mail" placeholder="请输入邮箱" clearable :style="{ width: '100%' }">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24" v-if="formData.type == 1">
                    <el-form-item label="Bark地址" prop="barkUrl">
                        <el-input v-model="formData.barkUrl" placeholder="请输入Bark地址" clearable
                            :style="{ width: '100%' }">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item size="large">
                        <el-button type="primary" @click="submitMailForm(formRef)">保存</el-button>
                        <el-button @click="settingOuterVisible = false">取消</el-button>
                        <el-button @click="resetForm(formRef)">重置</el-button>
                    </el-form-item>
                </el-col>
            </el-form>
        </el-row>
    </el-dialog>
    <!-- 通知设置对话框 end-->

    <div ref="aiText">

    </div>
</template>
<script setup lang='ts'>
import { ref, watch, onMounted, defineAsyncComponent } from 'vue';
import type { FormInstance, FormRules, ComponentSize } from 'element-plus';
import { showErrorMsg, showSuccessMsg, resetForm, type ApiResponse } from '@/api/common';
import { saveNotifySetting, getNotifySetting, stream } from '@/api/notify/notify';
import type { NotifyMailSetting } from '@/api/notify/notify';
const CanvasTree = defineAsyncComponent(() => import('@/views/background/canvasTree.vue'))
const radio = ref<number | null>(null);
const title = ref('邮箱设置');
const settingOuterVisible = ref<boolean>(false);
const formRef = ref<FormInstance>();
const formData = ref<NotifyMailSetting>({
    id: null,
    type: null,
    mail: '',
    barkUrl: '',
})
const formSize = ref<ComponentSize>('default')
const mailSettingFunc = () => {
    formData.value.type = 0;
    getSetting();
    settingOuterVisible.value = true;
}
const barkSettingFunc = () => {
    formData.value.type = 1;
    getSetting();
    settingOuterVisible.value = true;
}
const getSetting = () => {
    getNotifySetting().then((res: ApiResponse<NotifyMailSetting>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            if (res.data) {
                formData.value.id = res.data.id;
                formData.value.mail = res.data.mail;
                formData.value.barkUrl = res.data.barkUrl;
                radio.value = res.data.type;
            }
        }
    })
}
const submitMailForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            saveNotifySetting(formData.value).then((res: ApiResponse<string>) => {
                if (res.status != 200) {
                    showErrorMsg(res.msg);
                } else {
                    showSuccessMsg("设置成功");
                    getSetting();
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
let rules = ref<FormRules<NotifyMailSetting>>({
    mail: [{
        required: false,
        message: '请输入邮箱',
        trigger: 'change'
    }],
    barkUrl: [{
        required: false,
        message: '请输入Bark地址',
        trigger: 'change'
    }]
})
watch(() => formData.value.type, (newValue) => {
    if (newValue === 0) {
        rules.value.mail = [];
        rules.value.mail.push({
            required: true,
            message: '请输入邮箱',
            trigger: ['change', 'blur']
        })
        rules.value.barkUrl = [];
        rules.value.barkUrl.push({
            required: false,
            message: '请输入Bark地址',
            trigger: ['change', 'blur']
        })
    } else if (newValue === 1) {
        rules.value.mail = [];
        rules.value.mail.push({
            required: false,
            message: '请输入邮箱',
            trigger: ['change', 'blur']
        })
        rules.value.barkUrl = [];
        rules.value.barkUrl.push({
            required: true,
            message: '请输入Bark地址',
            trigger: ['change', 'blur']
        })
    }
});

onMounted(() => {
    getSetting();
})
const url = 'http://localhost:2048/test/stream';
async function getResponse(content: string) {
    // 这个await是等待响应头
    const resp = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ content }),
    })
    // 这个await是等待整个响应体全部完成。流式读取就不能用这个
    // const text = await resp.text();
    // console.log(text);
    const reader = resp.body?.getReader();
    const textDecoder = new TextDecoder();
    while (1) {
        // const { done, value } = await reader?.read();
        // if (done) {
        //     break;
        // }
        // console.log(done, textDecoder.decode(value));
    }
}
// getResponse('');

async function getResponse1(content: string): Promise<void> {
    try {
        const response = await stream(null);
        // const response = await axios.post(url, { content }, { responseType: 'stream' });

        // Create a reader from the response stream
        const reader = response.data.getReader();
        const textDecoder = new TextDecoder();

        while (true) {
            const { done, value } = await reader.read();

            if (done) {
                break;
            }

            if (value) {
                console.log(textDecoder.decode(value));
            }
        }
    } catch (error) {
        console.error('Error in getResponse:', error);
    }
}
// getResponse1('');

async function getResponse2(content: string): Promise<void> {
    try {
        const response = await fetch(import.meta.env.VITE_APP_BASE_API + '/test/stream', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ content }),
        });

        const reader = response.body?.getReader();
        const textDecoder = new TextDecoder();

        while (true) {
            const { done, value } = await reader!.read(); // 使用非空断言（!）确保 reader 不为空

            if (done) {
                break;
            }

            if (value) {
                console.log(textDecoder.decode(value));
            }
        }
    } catch (error) {
        console.error('Error in getResponse:', error);
    }
}
getResponse2('');

</script>
<style scoped></style>